package ru.tests;

import ru.housewife.model.Region;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class LoadRegions {

    public static void main(String[] args) throws IOException {

        System.setProperty("file.encoding", "UTF8");

        String srcStr = loadRegionsStrFromFile("regions.txt");

        Map<Long, Region> regions = new HashMap<Long, Region>();

        while(true) {

            int indx1 = srcStr.indexOf("':{p:'");
            if (indx1 == -1) {
                break;
            }
            int indx2 = srcStr.indexOf("'},");
            int regId = Integer.parseInt(srcStr.substring(1, indx1));
            String substr2 = srcStr.substring(indx1 + "':{p:'".length(), indx2);

            int parentRegId = Integer.parseInt(substr2.substring(0, substr2.indexOf("',c:")));
            String name = substr2.substring(substr2.indexOf(",n:'") + ",n:'".length());

            //System.out.println("id[" + regId + "], parentId[" + parentRegId + "], name[" + name + "]");

            srcStr = srcStr.substring(indx2 + "'},".length());

            Region region = new Region();

            region.setId((long) regId);
            region.setName(name);
            Region parent = new Region();
            parent.setId((long) parentRegId);
            region.setParent(parent);
            regions.put(region.getId(), region);
        }

        List<Region> roots = findChildRegions(regions, -1);

        processRegions(roots, regions, 1);

        System.out.println("1");

        recalcIds(roots);

        System.out.println("2");


        printSql(roots);

    }

    private static void recalcIds(List<Region> regions) {
        for (Region region : regions) {
            region.setId(getNextId());
            recalcIds(region.getChilds());
        }
    }

    private static long idSequence = 0;
    private static long getNextId() {
        idSequence++;
        return idSequence;
    }

    private static void printSql(List<Region> regions) {
        for (Region region : regions) {

            if (region.getParent().getId() > 0) {
                System.out.println("insert into REGIONS (ID, NAME, SUPPORT_PRICE_CALC, PARENT_ID) values (" + region.getId() + ", '" + region.getName().replace("'", "''") + "', " + region.isSupportPriceCalc() + ", " + region.getParent().getId() + ");");
            } else {
                System.out.println("insert into REGIONS (ID, NAME, SUPPORT_PRICE_CALC) values (" + region.getId() + ", '" + region.getName().replace("'", "''") + "', " + region.isSupportPriceCalc() + ");");
            }

            printSql(region.getChilds());
        }
    }

    private static void processRegions(List<Region> regions, Map<Long, Region> regionsMap, int level) {
        for (Region region : regions) {
            if (level == 3) {
                region.setSupportPriceCalc(true);
            }
            List<Region> childs = findChildRegions(regionsMap, region.getId());
            for (Region child : childs) {
                child.setParent(region);
            }
            region.setChilds(childs);
            processRegions(childs, regionsMap, level+1);
        }
    }

    private static List<Region> findChildRegions(Map<Long, Region> regions, long parentId) {
        List<Region> result = new ArrayList<Region>();
        for (Region reg : regions.values()) {
            if (reg.getParent().getId().equals(parentId)) {
                result.add(reg);
            }
        }
        return result;
    }

    private static String loadRegionsStrFromFile(String s) throws IOException {

//        URL url = LoadRegions.class.getResource("/regs.txt");
        URL url = LoadRegions.class.getResource("/regs_rus.txt");
        File f = new File(url.getFile());
        byte [] buf = new byte[(int) f.length()];
        FileInputStream fin = new FileInputStream(f);
        fin.read(buf);
        fin.close();

        return new String(buf, "UTF8");

    }

}
